package demo03_pub_sub;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeoutException;

/**
 * @Description 发布订阅模式的消息消费者
 * @Author shihan
 * @Date 2020/12/20 14:49
 * @Version 1.0
 */
public class PSConsumer {

    public static void main(String[] args) throws NoSuchAlgorithmException, KeyManagementException, URISyntaxException, IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setUri("amqp://root:123456@192.168.66.129:5672/%2f");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        // 声明一个 fanout 类型的 Exchange，要和生产者声明的 Exchange 保持一致
        channel.exchangeDeclare(PSProducer.EXCHANGE_NAME_FANOUT, BuiltinExchangeType.FANOUT);
        // 声明一个临时队列，名称由系统随机命名 -- 只需要拿到临时队列系统命名的名称即可；
        String queueName = channel.queueDeclare().getQueue();

        // 绑定 Queue 和 Exchange（Routing key 置为空串即可），用来接收上线后的消息
        channel.queueBind(queueName,PSProducer.EXCHANGE_NAME_FANOUT,"");
        // 监听临时队列中的消息，回调触发执行
        channel.basicConsume(queueName, new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                System.out.println("接收到的消息：" + new String(message.getBody(),"utf-8"));
            }
        }, new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
                // do nothing! 失败后的处理！
            }
        });

    }

}
